{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "ename": "NameError",
     "evalue": "name 'os' is not defined",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mNameError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-1-f135592a7012>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[1;32m      5\u001b[0m \u001b[0;32mfrom\u001b[0m \u001b[0mtqdm\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mtqdm\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m      6\u001b[0m \u001b[0mrandom\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mseed\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 7\u001b[0;31m \u001b[0mconf_path\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mos\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mpath\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mdirname\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mos\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mpath\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mabspath\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0m__file__\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m      8\u001b[0m \u001b[0mwork_path\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mos\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mpath\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mdirname\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mos\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mpath\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mdirname\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mconf_path\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m      9\u001b[0m \u001b[0mbase_dir\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mos\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mpath\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mjoin\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mwork_path\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m\"data\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;31mNameError\u001b[0m: name 'os' is not defined"
     ]
    }
   ],
   "source": [
    "import pkuseg\n",
    "import jieba\n",
    "import random\n",
    "import pandas as pd\n",
    "from tqdm import tqdm\n",
    "random.seed(1)\n",
    "conf_path = os.path.dirname(os.path.abspath(__file__))\n",
    "work_path = os.path.dirname(os.path.dirname(conf_path))\n",
    "base_dir = os.path.join(work_path, \"data\")\n",
    "# base_dir = '../data/'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def is_chinese(string):\n",
    "    for uchar in string:\n",
    "        if uchar >= u'\\u4e00' and uchar <= u'\\u9fa5':\n",
    "            return True\n",
    "        else:\n",
    "            return False\n",
    "\n",
    "def filter_all(segs):\n",
    "    segs = filter(lambda x:x not in stopwords, segs)  #去掉停用词\n",
    "#     segs = filter(lambda x:len(x)>1,segs)\n",
    "    segs = filter(lambda x:is_chinese(x)==True, segs)\n",
    "    segs = filter(lambda x:x != '了' and x != '的', segs)\n",
    "    string_list = []\n",
    "    for i in segs:\n",
    "        string_list.append(i)\n",
    "    # TODO\n",
    "    string = (' '.join(string_list))\n",
    "    return string\n",
    "        \n",
    "# pku > jieba\n",
    "def dump_file(df, filename, mode='train'):\n",
    "    seg = pkuseg.pkuseg(model_name='web')\n",
    "    with open(filename, 'w',encoding='utf-8') as f:\n",
    "        for i in df.index.values:\n",
    "            if random.random() > 0.5:\n",
    "                segs = seg.cut(df.text[i])\n",
    "            else:\n",
    "                segs = jieba.cut(df.text[i])\n",
    "            string = filter_all(segs)\n",
    "            if mode == 'train' or mode == 'val':\n",
    "                string = df.stance[i] + ' ' + string\n",
    "                string = string.lstrip()\n",
    "            f.write(string + '\\n')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df_source = pd.read_csv(base_dir+'train.csv',delimiter=\"\\t\")\n",
    "df_extra = pd.read_csv(base_dir+'test_pred.csv',index_col=0)\n",
    "df = pd.concat([df_extra, df_source])\n",
    "df.dropna(inplace=True)\n",
    "\n",
    "mapping = {'FAVOR':'__label__A', 'AGAINST':'__label__B', 'NONE':'__label__C'}\n",
    "df['stance'] = df['stance'].map(mapping)\n",
    "\n",
    "df.drop_duplicates(subset='text', keep='first', inplace=True)\n",
    "df.index = range(len(df))\n",
    "\n",
    "stopwords = []\n",
    "for line in open('stopwords.txt', encoding='utf-8'):\n",
    "    stopwords.append(line)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def process_extra_data(df_extra):\n",
    "    df_a = df_extra[df.stance == '__label__A'].sample(frac=1)\n",
    "    df_b = df_extra[df.stance == '__label__B'].sample(frac=1)\n",
    "    df_c = df_extra[df.stance == '__label__C'].sample(frac=1)\n",
    "    \n",
    "    dfc = pd.DataFrame(columns=['target', 'text', 'stance'])\n",
    "    \n",
    "    for i in range(len(df_c)):\n",
    "        if i != len(df_c) - 1:\n",
    "            string_a = filter_all(jieba.cut(df_c.iloc[i].text))\n",
    "            string_a_list = string_a.split(' ')\n",
    "            string_a_list = random.sample(string_a_list, 2)\n",
    "            string_b = filter_all(jieba.cut(df_c.iloc[i+1].text))\n",
    "            string_b_list = string_b.split(' ')\n",
    "            string_b_list = random.sample(string_b_list, 2)\n",
    "            string_a_list.extend(string_b_list)\n",
    "            \n",
    "            data = {'target':['whatever'], 'text':[','.join(string_a_list)], 'stance':['__label__A']}\n",
    "            df_tmp = pd.DataFrame(data)\n",
    "            dfc = pd.concat([df_tmp,df_c])\n",
    "    \n",
    "    return dfc"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df_c = df.loc[df.stance == '__label__C'].sample(frac=0.4)\n",
    "df_a = df.loc[df.stance == '__label__A'].sample(frac=0.04)\n",
    "df_b = df.loc[df.stance == '__label__B'].sample(frac=0.04)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = df.sample(frac=1)\n",
    "df['stance'].value_counts()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_len = int(len(df) * 0.75)\n",
    "df_train = df.iloc[:train_len]\n",
    "df_val = df.iloc[train_len:]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "dump_file(df_train, 'train.txt', 'train')\n",
    "dump_file(df_val, 'val.txt', 'val')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def read_data_file(path):\n",
    "    seg = pkuseg.pkuseg(model_name='web')\n",
    "    lines = open(path, 'r', encoding='utf-8').read().splitlines()\n",
    "    x_list = []\n",
    "    y_list = []\n",
    "    for line in tqdm(lines):\n",
    "    rows = line.split('\\t')\n",
    "    if len(rows) > 1:\n",
    "        if random.random() > 0.5:\n",
    "            segs = jieba.cut(rows[0])\n",
    "        else:\n",
    "            segs = seg.cut(rows[0])\n",
    "    x_list.append(filter_all(segs))\n",
    "    y_list.append(rows[1])\n",
    "    return x_list, y_list"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_x, train_y = read_data_file(base_dir+'train.txt')\n",
    "val_x, val_y = read_data_file(base_dir+'val.txt')\n",
    "test_x, test_y = read_data_file(base_dir+'test.txt')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import kashgari\n",
    "from kashgari.embeddings import BERTEmbedding\n",
    "from kashgari.embeddings import WordEmbedding\n",
    "# embedding = BERTEmbedding(base_dir+'chinese_L-12_H-768_A-12/', task=kashgari.CLASSIFICATION)\n",
    "embedding = WordEmbedding(base_dir+'sgns.weibo.bigram-char', task=kashgari.CLASSIFICATION)\n",
    "kashgari.config.use_cudnn_cell = True"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from kashgari.tasks.classification import BiLSTM_Model\n",
    "\n",
    "hyper = BiLSTM_Model.get_default_hyper_parameters()\n",
    "hyper['layer_bi_lstm']['units']=32\n",
    "# hyper['spatial_dropout']['rate']=0.5\n",
    "# hyper['dropout']['rate']=0.5\n",
    "# hyper['dropout_rnn']['rate']=0.5\n",
    "model = BiLSTM_Model(embedding, hyper_parameters=hyper)\n",
    "model.fit(train_x, train_y, val_x, val_y, batch_size=32, epochs=20)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "model.evaluate(test_x, test_y)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "test = pd.read_csv(base_dir+'test.csv', delimiter='\\t')\n",
    "labels = []\n",
    "for line in tqdm(test.text.values):\n",
    "    x_list = filter_all(jieba.cut(line, cut_all=True))\n",
    "    labels.append(model.predict(x_list)[0])\n",
    "        \n",
    "test['idx'] = range(len(test))\n",
    "test['stance'] = labels\n",
    "test = test.drop(['target', 'text'], axis=1)\n",
    "\n",
    "test.to_csv(base_dir+'test_pred.csv',index=False,header=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "BiLSTM_Model.get_default_hyper_parameters()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
